package com.stock;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Map;

/**
 * Created by kevin on 15/12/24.
 */
public class MapUtils {


    public static <T> T map2obj(Map<String,String> map,Class<T> t){
        T obj = null;
        try {
            obj = t.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Field[] declaredFields = t.getDeclaredFields();
        for(Field f:declaredFields){
            String name = f.getName();
            String value = map.get(name);
            if(value==null||"".equals(value)){
                //Logger.info("{} value is null or value not found,skipped.",name);
                continue;
            }
            //Logger.info("name:{},value:{}",name,value);
            try {
                String type = f.getType().getSimpleName();
                f.setAccessible(true);
                if("short".equalsIgnoreCase(type)) {
                    f.set(obj,new Short(value));
                }else if("int".equalsIgnoreCase(type)) {
                    f.set(obj,new Integer(value));
                }else if("integer".equalsIgnoreCase(type)) {
                    f.set(obj,new Integer(value));
                }else if("long".equalsIgnoreCase(type)) {
                    f.set(obj,new Long(value));
                }else if("float".equalsIgnoreCase(type)) {
                    f.set(obj,new Float(value));
                }else if("double".equalsIgnoreCase(type)) {
                    f.set(obj,new Double(value));
                }else if("string".equalsIgnoreCase(type)) {
                    f.set(obj,value);
                }else if("BigDecimal".equalsIgnoreCase(type)) {
                    f.set(obj,new BigDecimal(value));
                }else{
                    //Logger.info("type {} not found,skipped.",type);
                    continue;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return obj;

    }
}
